<!-- sku管理 - 综合表单页面 -->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />

    <ex_super_table_page v-bind="option" ref="SuperTablePage" @search="searchChange"
      @selection-change="e => selection = e">

    </ex_super_table_page>

    <ex_super_dialog_form ref="auditBatchDialog" v-bind="auditBatchDialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>
    <ex_super_dialog_form ref="auditDialog" v-bind="auditDialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>




    <print_sku ref="print_sku" itemKey="id" />

    <mms_batch_set ref="mms_batch_set"></mms_batch_set>
    <!-- 商品差异设置    -->
    <mms_sku_diff_setting ref="mms_sku_diff_setting"></mms_sku_diff_setting>

    <!-- 走货属性设置 -->
    <ex_super_dialog_form ref="formRef" v-bind="formConfig" @afterSubmitSuccess="reload" />
  </div>
</template>
<script>
import business_function from "@/common/business_function"

import print_sku from '@/component/print/print_sku'
import superTablePageFunction from '@/mixin/super-table-page-function';
import page_table_model_manage from '@/mixin/page_table_model_manage';
import mms_batch_set from "@/component/mms/mms_batch_set.vue";
import emitOnFunction from '@/mixin/emit-on-function';
import mms_sku_diff_setting from "@/component/mms/mms_sku_diff_setting.vue";

let emitKey = 'sku>sku_manage'
export default {
  title: 'label_sku_manage',
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: { mms_sku_diff_setting, print_sku, mms_batch_set },
  data() {
    return {
      selection: [],
      auditBatchDialog: false,

      skuStatus: "",
      skuCountByStatus: {
        totalCount: 0,
        submitCount: 0,
        processCount: 0,
        discardCount: 0,
        failCount: 0,
        successCount: 0
      },
      status_map: {
        "ENABLE": 'successCount',
        'WAIT_AUDIT': 'processCount',
        "DISCARD": 'discardCount',
        "REJECT": 'failCount',
      },
      // auditDialog: false,
      // auditForm: {
      //   id: '',
      //   skuBarcode: '',
      //   opResult: 'Y',
      //   idList: [],
      // },

      option: {
        search: {
          default: { skuStatus: "" },
          resetFieldFun: (def, org) => { def.skuStatus = org.skuStatus; return def },
          formDataHandle: (data) => {
            if (data.categIds && data.categIds.length > 0) {
              data.categId = data.categIds[data.categIds.length - 1]
            } else {
              data.categId = null
            }
            return data
          },
          model: [
            {
              key: 'skuStatus', label: 'label_status', itemClass: "w_fill",
              type: 'select', enum: 'SkuStatusEnum',
              render: (h, { data }) => {
                const list = Object.keys(this.status_map)
                  .map(it => (
                    <el-radio-button key={it} label={it}>
                      {this.$enumShow(it, 'SkuStatusEnum')}({this.skuCountByStatus[this.status_map[it]]})
                    </el-radio-button>
                  ))
                return (<el-radio-group value={data.skuStatus}
                  onInput={e => {
                    this.$set(data, 'skuStatus', e)
                    this.$refs.SuperTablePage.loadDataForSearch()
                  }}>
                  <el-radio-button key="" label="">
                    {this.$tt("label_all")}
                  </el-radio-button>
                  {list}
                </el-radio-group>
                )
              }
            },
            { label: "label_keyword", key: "keyword", type: 'input', attrs: { placeholder: `${this.$tt('label_name')} / ${this.$tt('label_code')} / ${this.$tt('label_barcode')}`, }, },
            { label: "label_customer", key: "customerId", type: 'common_customer_choose' },
            {
              key: 'categIds',
              label: 'label_sku_categ',
              render: (h, { data }) => {
                return <sku_categ_cascader categList={data.categList}
                  onChangeCategList={e => {
                    this.$set(data, 'categList', e)
                  }}
                  onChange={e => {
                    this.$set(data, 'categIds', e)
                  }}
                />
              }
            },
            {
              label: "label_is_upload_certificate", key: "isCertificate", type: 'select', enum: 'YesOrNoEnum',
            },
            {
              label: "label_is_electrify", key: "isElectrify", type: 'select', enum: 'YesOrNoEnum',
            },
            {
              label: "label_transport_goods",
              key: "cargoPropertyId",
              render: (h, { data }) => {
                return <transport_goods_select value={data.cargoPropertyCode} onChangeItem={e=>{
                    if(!e) e={code:null,id:null}
                    this.$set(data, 'cargoPropertyCode', e.code)
                    this.$set(data, 'cargoPropertyId', e.id)
                  }}/>
              }
            },

          ],
        },
        action: [
          {
            label: 'label_add_sku', attrs: { icon: "el-icon-plus" },
            auth: 'oms_sku_manage_edit',
            click: () => {
              this.$router.push({ path: '/page/mms/sku/sku_operate', query: { emitKey } });
            }
          },
          {
            label: 'label_sku_audit', attrs: {}, click: () => {
              if (this.selection.length == 0) {
                this.$message.error(this.$t('tip_not_setlect_data'));
                return;
              }
              // let idList = [];
              // this.selection.forEach(e => idList.push(e.id));
              this.$refs.auditBatchDialog.showNew({
                title: this.$t('label_sku_audit'),
                data: {

                  idList: this.selection.map(e => (e.id)),
                }
              })
              // this.auditForm.idList = idList
              // this.auditBatchDialog = true;
            }
          },

          {
            label: 'label_batch_operate',
            auth: 'oms_sku_manage_edit',
            click: (row) => this.batchSet(this.selection)
          },
        ],
        actionExtra: [
          {
            label: 'label_transport_goods_config', click: () => this.transportGoodsConfig()
          },
          {
            label: 'label_print_barcode', attrs: { type: "primary" }, click: (row) => this.print(this.selection)
          },
          {
            auth: 'oms_sku_manage_export',
            label: 'label_export', click: this.exportExcel
          },
          {
            label: 'label_diff_settings', attrs: {},
            auth: 'oms_sku_manage_diff_settings',
            click: () => {
              if (_.isEmpty(this.selection)) {
                this.$message.error(this.$tt('tip_please_select_first_customer'))
                return
              }
              // else if (this.selection.some(row => row.skuStatus != "WAIT_AUDIT")) {
              //   return this.$message.error(this.$t('tip_status_error_no_operate'))
              // }
              this.$refs.mms_sku_diff_setting.showBySkus(this.selection)
            }
          },
          {
            label: { _key: 'label_type_download_import_temp', type: "" }, auth: 'oms_sku_manage_edit',
            click: this.downloadImportTemp
          },
          {
            auth: 'oms_sku_manage_edit',
            render: (h) => (<button_select_file onInput={files => this.uploadFile(files)} >
              {this.$tt('label_import')}
              <i class="el-icon-upload2 el-icon--right"></i>
            </button_select_file>),
          },
          // { label: 'label_download_excel_import_temp', click: this.downloadImportTemp },
        ],
        table: {
          url: "/mms-api/sku/MmsSkuInfoRpc/selectPage.json",
          model: this.init_table_model(),
        }
        ,

      },
      auditBatchDialog: {
        customClass: 'dialog_auto',
        submitUrl: '/mms-api/sku/MmsSkuInfoRpc/auditSkuInfoBatch.json',
        submitDataHandle: (data) => {
          return {
            idList: data.idList,
            opResult: data.opResult,
          }
        },
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            {
              key: 'tip', label: 'label_tip',
              render: (h, { data, item }) => {
                const tip = this.$t('tip_has_select_count_sku', { count: data.idList ? data.idList.length : '' })
                return (<el-alert title={tip} type="warning" closable={false} />)
              }
            },
            {
              key: 'opResult', label: 'label_audit_result', type: 'select',
              attrs: {
                i18n: true,
                items: [
                  { label: 'enum_examine_pass', value: 'Y' }, { label: 'enum_examine_reject', value: 'N' },
                ],
              },
            },
          ],
          rules: {
            'opResult': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
          },
        }
      },
      auditDialog: {
        customClass: 'dialog_auto',
        submitUrl: '/mms-api/sku/MmsSkuInfoRpc/auditSkuInfo.json',
        submitDataHandle: (data) => {
          return {
            id: data.id,
            opResult: data.opResult,
          }
        },
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            {
              key: 'customerCode', label: 'label_customer_info',
              render: (h, { data, item }) => this.$renderText(h, this.$formatNameCode(data.customerName, data.customerCode))
            },
            {
              key: 'skuOnlyCode', label: 'label_sku_only_code',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])
            },
            {
              key: 'skuBarcode', label: 'label_sku_code',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])
            },
            {
              key: 'skuName', label: 'label_sku_name',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])
            },
            {
              key: 'skuNameEn', label: 'label_sku_name_en',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])
            },

            {
              key: 'opResult', label: 'label_audit_result', type: 'select',
              attrs: {
                i18n: true,
                items: [
                  { label: 'enum_examine_pass', value: 'Y' }, { label: 'enum_examine_reject', value: 'N' },
                ],
              },
            },
          ],
          rules: {
            'opResult': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
          },
        }
      },
      formConfig: {
        customClass: "dialog_auto",
        submitDataHandle: (data) => {
          data.skuUpdateList.map(item => {
            item.cargoPropertyCode = data.cargoPropertyCode
            item.cargoPropertyId = data.cargoPropertyId
            item.cargoPropertyName = data.cargoPropertyName
            return item
          })
          return data
        },
        form: {
          itemClass: "form_item_default",
          inputClass: "form_input_default",
          // formClass: "form_default_col2 flex_row_wrap",
          default: {
            skuUpdateList: []
          },
          model: [
            {
              key: "code",
              formType: 'text',
              render: (h, { data }) => {
                return this.$t(`label_selected_products`, [data.skuUpdateList.length])
              }
            },
            {
              key: "cargoPropertyCode",
              label: "label_transport_goods",
              render: (h, { data }) => {
                return h("transport_goods_select", {
                  class: "form_input_default",
                  props: {
                    value: data.cargoPropertyCode
                  },
                  on: {
                    changeItem: (e) => {
                      this.$set(data, 'cargoPropertyCode', e.code)
                      this.$set(data, 'cargoPropertyId', e.id)
                      this.$set(data, 'cargoPropertyName', e.name)
                    },
                  },
                });
              },
            }
          ],
          rules: {
            cargoPropertyCode: {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            }
          }
        },

      }
    };
  },
  methods: {

    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },

        {
          type: 'expandDesc', 'width': 80,
          expandDesc: {
            ...this.$defaultDescAttrs,
            model: [],
          },
        },
        {
          key: 'customerCode', label: 'label_customer_info', 'width': 180, 'show-overflow-tooltip': true,
          render: (h, { row, }) => this.$renderText(h, this.$formatNameCode(row.customerName, row.customerCode))

        },
        { key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': 180, },
        { key: 'skuBarcode', label: 'label_sku_code', 'min-width': 150, },

        // {
        //   key: 'isUploadImg', label: 'label_is_upload_img', 'width': 120, 'show-overflow-tooltip': true, keyShow: 'expandDesc',
        //   formatter: (r, c, v, i) => this.$enumShow(v, 'YesOrNoEnum')
        // },
        { key: 'skuName', label: 'label_sku_name', 'min-width': 130, 'show-overflow-tooltip': true, },
        { key: 'skuNameEn', label: 'label_sku_name_en', 'min-width': 130, 'show-overflow-tooltip': true, },
        { label: "label_transport_goods", key: "cargoPropertyName",'min-width': 130, 'show-overflow-tooltip': true,formatter: (r, c, v, i) => this.$formatNameCode(v, r.cargoPropertyCode) },
        {
          key: 'categList', label: 'label_sku_categ', 'width': 240, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => v ? v.map(it => it.categoryName).join("/") : this.$tt("data_none")

        },
        // {
        //   key: 'isElectrify',
        //   label: 'label_is_electrify',
        //   'width': 100, keyShow: 'expandDesc', 'show-overflow-tooltip': true,
        //   formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum"),
        // },
        // {
        //   key: 'isCertificate', label: 'label_is_upload_certificate', 'show-overflow-tooltip': true, keyShow: 'expandDesc',
        //   formatter: (r, c, v, i) => this.$enumShow(v, 'YesOrNoEnum')
        // },
        {
          key: 'skuDeclaredValue', label: 'label_declared_value', 'width': 140, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$formatNameCode(v, r.currencyCode)
        },
        {
          key: 'skuSize', label: 'label_length_width_height_unit', 'min-width': 180, 'show-overflow-tooltip': true,
          attrs: {
            formatter: (r, c, v, i) => {
              return r.skuLength + '*' + r.skuWidth + '*' + r.skuHeight
            }
          }
        },
        {
          key: 'categList', label: 'label_belong_category', 'width': 240, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => v ? v.map(it => it.categoryName).join("/") : this.$tt("data_none")
        },
        {
          key: 'skuWeight', label: 'label_weight', 'width': 100, 'show-overflow-tooltip': true, keyShow: 'expandDesc',
          formatter: (r, c, v, i) => this.$addUnitQuick.Weight(v),
        },
        {
          key: 'skuLength', label: 'label_length', 'width': 100, 'show-overflow-tooltip': true, keyShow: 'expandDesc',
          formatter: (r, c, v, i) => this.$addUnitQuick.Dimen(v),
        },
        {
          key: 'skuWidth', label: 'label_width', 'width': 100, 'show-overflow-tooltip': true, keyShow: 'expandDesc',
          formatter: (r, c, v, i) => this.$addUnitQuick.Dimen(v),
        },
        {
          key: 'skuHeight', label: 'label_height', 'width': 100, 'show-overflow-tooltip': true, keyShow: 'expandDesc',
          formatter: (r, c, v, i) => this.$addUnitQuick.Dimen(v),
        },
        {
          key: 'skuStatus', label: 'label_status', 'width': 140, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, 'SkuStatusEnum')
        },
        { key: 'gmtModify', label: 'label_update_time', formatter: (r, c, v, i) => this.$dateFormat(v) },
        {
          type: 'operate', width: 210, fixed: 'right', operate: [
            {
              label: 'label_edit',
              auth: 'oms_sku_manage_edit',
              click: (row) => {
                this.editOrder(row)
              }
            },
            {
              label: 'label_delete',
              auth: 'oms_sku_manage_delete',
              type: "confirm-button",
              url: '/mms-api/sku/MmsSkuInfoRpc/remove.json',
              buttonClass: "button_text_danger", confirmButtonType: 'danger',
              message: 'text_confirm_sure_delete',
              params: (row) => { return { "id": row["id"] } }, done: ['reload', 'tip']
            },
            {
              label: 'label_fms_account_apply_audit',

              disabled: (row) => row.skuStatus != "WAIT_AUDIT",
              click: (row) => {
                // this.auditForm.id = row.id
                // this.auditForm.skuBarcode = row.skuBarcode
                // this.auditDialog = true
                this.$refs.auditDialog.showNew({
                  title: this.$t("label_sku_audit"),
                  data: row,
                })
              }
            },

            {
              type: 'more',
              items: [
                { label: 'label_view_detail', click: (row) => this.clickDetail(row) },
                {
                  label: 'label_copy_new', auth: 'oms_sku_manage_edit',
                  click: (row) => this.copyOrder(row),
                },
                { label: "label_print_barcode", click: (row) => this.print([row]) },
                {
                  label: 'label_diff_settings', auth: 'oms_sku_manage_diff_settings', click: (row) => {
                    // if (row.skuStatus != "WAIT_AUDIT") {
                    //   return this.$message.error(this.$t('tip_status_error_no_operate'))
                    // }
                    this.$refs.mms_sku_diff_setting.showBySkuIndex(row)
                  }
                }
              ],
            }
          ],
        }
      ]
    },
    changeStatus(e) {
      this.skuStatus = e
      this.getSuperTablePage().loadDataForSearch()
    },
    searchChange() {
      this.$ajax({
        url: "/mms-api/sku/MmsSkuInfoRpc/selectPageCount.json",
        data: this.getSuperTablePage().getSearchFormData(),
        success: (res) => {
          this.skuCountByStatus = res.data
        }
      })
    },

    clickDetail(row) {
      this.$router.push({ path: '/page/mms/sku/sku_detail', query: { id: row.id, emitKey } })
    },
    copyOrder(row) {
      this.$router.push({
        path: '/page/mms/sku/sku_operate', query: { id: row.id, emitKey, edit: true, copy: true, }
      });
    },
    editOrder(row) {
      this.$router.push({
        path: '/page/mms/sku/sku_operate', query: { id: row.id, emitKey, edit: true, }
      });
    },
    print(rows) {
      if (_.isEmpty(rows)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.$refs.print_sku.show(rows)
    },
    uploadFile(files) {
      this.$functionCommon({
        url: this.$url['mms/importExcel'],
        file: files[0],
        commonType: "import",
      })
    },
    exportExcel() {
      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: this.$refs.SuperTablePage.getSearchFormData(),
        model: this.option.search.model,
        selection: this.selection,
        callback: (selection, data) => {
          let params = {}
          if (!_.isEmpty(selection)) {
            params = {
              idList: selection.map(it => it.id)
            }
          } else {
            params = data
          }
          this.$functionCommon({
            url: this.$url['mms/exportExcel'],
            data: params,
          })
        }
      })
    },
    downloadImportTemp() {
      if (this.$clickFast()) return
      this.$downloadFile({
        window: true,
        url: this.$url['mms/downloadImportTemp']
      })
      // const a = document.createElement('a')
      // a.href = this.$url['mms/downloadImportTemp']
      // a.target = '_blank'
      // a.click()

    },

    batchSet(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_sku'))
      this.$refs.mms_batch_set.show(rows)
    },
    transportGoodsConfig() {
      if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt('tip_please_select_sku'))
      }
      const option = {
        title: this.$t('label_transport_goods'),
        submitUrl: '/mms-api/sku/MmsSkuInfoRpc/batchUpdate.json',
        data: {
          skuUpdateList: this.selection
        },
      }
      this["$refs"]["formRef"].showNew(option);
    }
  }
};

</script>
<style></style>
